package com.kcyu.sfherp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kcyu.sfherp.entity.WecomPostData;
import com.kcyu.sfherp.entity.utilEntity.WeComCheckInData;
import com.kcyu.sfherp.entity.utilEntity.WeComUserDTO;
import com.kcyu.sfherp.utils.RedisCache;
import com.squareup.okhttp.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WeComService {

    final String corpSecret = "BEYqnS4ynDBbdOh6WyijkJfZVAYbO-3UBdcfb-q4TNw";
    final String corpId = "ww8cc6318dfa44a24b";

    final String dkCorpSecret = "aEI57UXR6Ugsft0nrjgKsgNu4olehjeXKtL9_chCyY0";

    final String contractSecret = "AXede1IpxDFQk0H-6gfsV2Up6HBq4B5ZZP0rn8QiAyI";

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RestTemplate restTemplate;

    

    public String getAccessToken(String corpSecret) throws IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        Call call = client.newCall(request);
        Response response = call.execute();
        String s = response.body().string();
        JSONObject jsonObject = JSON.parseObject(s);
        s = jsonObject.getString("access_token");
        return s;
    }

    // 上传临时文件
//    public String uploadTempFile(String accessToken, File file, String type) throws IOException {
//        String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=file";
//        OkHttpClient client = new OkHttpClient();
//        RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM)
//                .addFormDataPart("media", "file", RequestBody.create(MediaType.parse("application/octet-stream"), file))
//                .build();
//        Request request = new Request.Builder().post(body).url(url).build();
//        Call call = client.newCall(request);
//        Response response = call.execute();
//        String s = response.body().string();
//        JSONObject jsonObject = JSON.parseObject(s);
//        s = jsonObject.getString("media_id");
//        return s;
//    }

    public void SendApplicationMessage(WecomPostData wecomPostData) {

        wecomPostData.setTouser(getNoticeMember());
        System.out.println(wecomPostData);
        String postData = JSON.toJSONString(wecomPostData);
        //        String postdata = "{\n" +
//                "   \"touser\" : \"YuJianCong\",\n" +
//                "   \"toparty\" : \"\",\n" +
//                "   \"totag\" : \"\",\n" +
//                "   \"msgtype\" : \"textcard\",\n" +
//                "   \"agentid\" : 1000004,\n" +
//                "   \"textcard\" : {\n" +
//                "       \"title\" : \"客户\", " +
//                "       \"description\" : \"您有新的提货工单，请及时查看\"," +
//                "       \"url\" : \"https://www.baidu.com\" " +
//                "   },\n" +
//                "   \"safe\":0,\n" +
//                "   \"enable_id_trans\": 0,\n" +
//                "   \"enable_duplicate_check\": 0,\n" +
//                "   \"duplicate_check_interval\": 1800\n" +
//                "}";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, postData);
        Request request = null;
        request = new Request.Builder()
                .url("http://43.138.112.173:9000/sendMessage")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 获取被通知的账号
    public String getNoticeMember() {
        List<String> memberList = redisCache.getCacheList("noticeMember");
        String nameString = "";
        if(memberList.size() == 0) {
            List<String> newMemberList = new ArrayList<>();
            newMemberList.add("YuJianCong");
            redisCache.setCacheList("noticeMember", newMemberList);
            nameString = newMemberList.stream().map(String::valueOf).collect(Collectors.joining("|"));
        } else {
            nameString = memberList.stream().map(String::valueOf).collect(Collectors.joining("|"));
        }
        return nameString;
    }

    public ArrayList<Map> getCompAllMember() {
        ArrayList<Map> result = restTemplate.getForObject("http://43.138.112.173:9000/getMember", ArrayList.class);
        System.out.println(result);
        return result;
    }

    public JSONArray getAllMember() throws IOException {
        String accessToken = getAccessToken(contractSecret);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token=" + accessToken;
        HashMap<Object, Object> map = new HashMap<>();
        String s = restTemplate.postForObject(url, null, String.class);
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray deptUser = jsonObject.getJSONArray("dept_user");

        return deptUser;
    }

    public String getCheckInDayData(String date, List<String> useridList) throws IOException, ParseException {
        // 获取当天开始的时间戳
        String startTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckin_daydata?access_token=" + getAccessToken(dkCorpSecret);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long start = Math.round(sdf.parse(startTime).getTime() / 1000);
        long end = Math.round(sdf.parse(endTime).getTime() / 1000);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("starttime", start);
        map.put("endtime", end);
        map.put("useridlist", useridList);

        System.out.println(map);
        String s = restTemplate.postForObject(url, map, String.class);
        return s;
    }

    public List<WeComCheckInData> getCheckInData(String date, List<String> useridList) throws IOException, ParseException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=" + getAccessToken(dkCorpSecret);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("opencheckindatatype", 3);

        String startTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long start = Math.round(sdf.parse(startTime).getTime() / 1000);
        long end = Math.round(sdf.parse(endTime).getTime() / 1000);
        map.put("starttime", start);
        map.put("endtime", end);
        map.put("useridlist", useridList);

        String s = restTemplate.postForObject(url, map, String.class);
        JSONObject object = JSON.parseObject(s);
        JSONArray checkindata = object.getJSONArray("checkindata");
        List<WeComCheckInData> weComCheckInData = JSONArray.parseArray(checkindata.toJSONString(), WeComCheckInData.class);
        return weComCheckInData;
    }

    public List<WeComUserDTO> getAllMemberDict() throws IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + getAccessToken(contractSecret) + "&department_id=1&fetch_child=1";
        String s = restTemplate.getForObject(url, String.class);
        log.info("获取企业成员列表: {}", s);
        JSONArray userlist = JSON.parseObject(s).getJSONArray("userlist");
        List<WeComUserDTO> weComMembers = JSONArray.parseArray(userlist.toJSONString(), WeComUserDTO.class);
        return weComMembers;
    }

    public void readMemberInfo(String userid) throws IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + getAccessToken(contractSecret) + "&userid=" + userid;
        String s = restTemplate.getForObject(url, String.class);
        System.out.println(s);
    }
}
